package com.shop.bookstore.controller;
import com.shop.bookstore.entity.Borrow;
import com.shop.bookstore.service.BorrowService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/borrow")
public class BorrowController {
    @Autowired
    BorrowService borrowService;
    @Autowired
    HttpServletRequest request;

    @RequestMapping("/borrowList")
    public String borrowMain(Model model) {
        Object username = request.getSession().getAttribute("username");
        if (username == null) {
            return "redirect:/";
        } else {
//            调用service方法查询到列表
            List<Borrow> borrowList = borrowService.findAll();
            System.out.println(borrowList);
//            将查询结果用model锁定
            model.addAttribute("data", borrowList);
            model.addAttribute("username", username);
//            return视图
            return "borrow/borrowList";
        }
    }

    @RequestMapping("/borrowAdd")
    public String borrowAdd(Model model) {
        Object username = request.getSession().getAttribute("username");
        if (username == null) {
            return "redirect:/";
        } else {
            model.addAttribute("username", username);
            return "borrow/borrowAdd";
        }

    }
    @RequestMapping("/borrowAddProcess")
    public String borrowAddProcess(@RequestParam String bookname, @RequestParam String borrow_time,
                                 @RequestParam String borrow_state, @RequestParam String back_time){
//      组装一个实体对象
        Borrow borrow = new Borrow(null,bookname,borrow_time,borrow_state,back_time);
//        调用service的add方法给数据库
        if (borrowService.add(borrow)==1){
//        如果返回ok，那么就进入商品管理首页
            return "redirect:/borrow/borrowList";
        }else{
            return "redirect:/borrow/borrowList";
        }
    }
    @RequestMapping("/borrowUpdate")
    public String borrowUpdate(Model model,@RequestParam String id){
        Object username = request.getSession().getAttribute("username");
        if(username==null){
            return "redirect:/";
        }else{
//        首先基于id查询出来该id记录里的所有数据信息
            Borrow borrow=new Borrow();
            borrow.setId(Integer.valueOf(id));
//        调用service方法查询出来该记录的数据信息
            Borrow borrowDB = borrowService.findOne(borrow);
//        2.将这些数据信息返回给视图
            model.addAttribute("data",borrowDB);
            model.addAttribute("username",username);
//        3.返回视图文件
            return "borrow/borrowUpdate";}
    }
}